<template>
  <div class="list">
    <ul class="item"
    v-for="item of letters" :ref="elem =>elems[item] = elem" @touchend="handleTouchEnd" @touchmove = "handleTouchMove" @touchstart.prevent = "handleTouchStart" @click="handleLetterClick" :key="item">{{item}}
    </ul>
  </div>
</template>

<script>
import { computed, onUpdated,ref} from 'vue'
export default{
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  setup(props, context){
    let touchStatus = false
    let startY = 0
    let timer = true
    const elems = ref([])
    const letters = computed(()=>{
      const letters = []
      for (let i in props.cities) {
        letters.push(i)
      }
      return letters      
    })
    onUpdated(()=>{
      startY = elems.value['A'].offsetTop
    })
    function handleLetterClick(e){
      context.emit('change', e.target.innerText)
    }
    function handleTouchStart(){
      touchStatus = true
    }
    function handleTouchEnd (e) {
        touchStatus = false
    }
    function handleTouchMove(e){
      if (touchStatus) {
    // 节流限制函数执行频率
        if (timer) {
          timer = false
          setTimeout(() => {
            const touchY = e.touches[0].clientY - 79
            const index = Math.floor((touchY - startY) / 20)
            if (index >= 0 && index < letters.value.length) {
              context.emit('change', letters.value[index])
            }
            timer = true
          }, 16)
        }
      }      
    }
    return {elems, letters,handleTouchStart, handleTouchMove, handleTouchEnd, handleLetterClick}
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
    display flex
    flex-direction column
    justify-content center
    position absolute
    top 1.58rem
    right 0
    bottom 0
    width .4rem
    color $bgColor
    .item
      text-align center
      line-height .4rem

</style>
